import type { ApiResponse, VoteRecord } from '../types/anime';
import { axiosInstance } from './axiosInstance';
import { API_PATHS } from './apiConfig';
import toastService from './toastService';

// 为动漫投票
export const voteForAnime = async (animeId: number): Promise<boolean> => {
  try {
    const response = await axiosInstance.post<ApiResponse<null>>(API_PATHS.VOTE.VOTE, { animeId });
    if (response.data.code !== 200) {
      toastService.error(response.data.msg);
      console.error('投票失败:', response.data.msg);
      return false;
    }
    return true;
  } catch (error) {
    console.error('投票失败:', error);
    // 如果是已经投过票的错误，返回false
    if (error instanceof Error && 'response' in error && 
        (error as any).response && (error as any).response.status === 400) {
      // 400错误由后端返回具体错误消息，不再重复提示
      return false;
    }
    throw error;
  }
};

// 获取用户投票记录
export const getUserVotedAnimes = async (page: number = 1, pageSize: number = 9): Promise<{data: VoteRecord[], total: number}> => {
  try {
    const response = await axiosInstance.get<ApiResponse<{data: VoteRecord[], total: number}>>(API_PATHS.VOTE.USER_LIST, {
      params: { page, pageSize }
    });
    if (response.data.code !== 200) {
      toastService.error(response.data.msg);
      console.error('获取用户投票记录失败:', response.data.msg);
      return { data: [], total: 0 };
    }
    // 直接返回response.data.data，因为后端现在返回的是包含data和total的Map对象
    return response.data.data;
  } catch (error) {
    console.error('获取用户投票记录失败:', error);
    // 降级处理：返回空数据和0总数
    return { data: [], total: 0 };
  }
};

// 检查用户是否已投票
export const checkUserVote = async (animeId: number): Promise<boolean> => {
  try {
    // 使用正确的API路径，假设CHECK路径应该是这样的格式
    const response = await axiosInstance.get<ApiResponse<boolean>>(`${API_PATHS.VOTE.VOTE}/check/${animeId}`);
    if (response.data.code !== 200) {
      toastService.error(response.data.msg);
      console.error('检查投票状态失败:', response.data.msg);
      return false;
    }
    return response.data.data;
  } catch (error) {
    console.error('检查投票状态失败:', error);
    throw error;
  }
};